<?php
namespace app\store\model;

use app\common\model\Record as RecordModel;
use think\facade\Db;

/**
 * 交易记录模型
 */
class Record extends RecordModel
{
    /**
     * 后台充值
	 *$recharge 接收表单数据（数组）
	 *$source 0为充值余额，1为充值积分
    */
    public function add($user_id, array $recharge, $source)
    {
    	$user = User::get($user_id);
        if($source == 1){
			//积分操作
			if(empty($recharge["points"]["value"])){
				$this->error = '积分变更数量不可为空';
				return false;
			}
			if(strpos($recharge["points"]["value"],".")){
				$this->error = '积分变更数量必须为整数';
				return false;
			}
			if(empty($recharge["points"]["shop_id"])){
				$this->error = '请选择门店';
				return false;
			}
			if($recharge["points"]["mode"] == 10){
				$user->score = ['inc',$recharge["points"]["value"]];//增加积分
			}
			if($recharge["points"]["mode"] == 20){
				$user->score = ['dec',$recharge["points"]["value"]];//扣减积分
			}
			if($recharge["points"]["mode"] == 30){
				$user->score = $recharge["points"]["value"];//重置积分
			}
			$data = [
				'mode' => 20, //后台充值
				'type' => 90, //积分
				'action' => $recharge['points']['mode'],
				'order_no' => order_no(),
				'money' => $recharge['points']['value'],
				'remark' => $recharge['points']['remark'],
				'shop_id' => $recharge['points']['shop_id'],
				'user_id' => $user_id,
				'applet_id' => self::$applet_id
			];
			// 开启事务
	        Db::startTrans();
	        try {
	        	$user->save();
	            $this->save($data);
	            Db::commit();
	            return true;
	        } catch (\Exception $e) {
	            Db::rollback();
	        }
	        return false;	
		}
		//充值余额
		if(empty($recharge["balance"]["value"])){
			$this->error = '变更金额不可为空';
			return false;
		}
		if(strpos($recharge["balance"]["value"],".")){
			$this->error = '变更金额必须为整数';
			return false;
		}
		if(empty($recharge["balance"]["shop_id"])){
			$this->error = '请选择门店';
			return false;
		}
		if($recharge["balance"]["mode"] == 10){
			$user->money = ['inc',$recharge["balance"]["value"]];//增加
		}
		if($recharge["balance"]["mode"] == 20){
			$user->money = ['dec',$recharge["balance"]["value"]];//扣减
		}
		if($recharge["balance"]["mode"] == 30){
			$user->money = $recharge["balance"]["value"];//重置
		}
		$data = [
			'mode' => 20, //后台充值
			'type' => 10, //余额
			'action' => $recharge['balance']['mode'],
			'order_no' => order_no(),
			'money' => $recharge['balance']['value'],
			'remark' => $recharge['balance']['remark'],
			'shop_id' => $recharge['balance']['shop_id'],
			'user_id' => $user_id,
			'applet_id' => self::$applet_id
		];
		// 开启事务
        Db::startTrans();
        try {
        	$user->save();
            $this->save($data);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

}
